<?php

namespace common\components\image_beds;

use common\Tools;
use GuzzleHttp\Client;
use yii\base\Component;

class EasyImage extends Component
{
    public $uploadUrl = '';
    public $token = '';

    public function upload($fileRoot)
    {
        $config = [
//            'verify' => YII_ENV_PROD,
        ];
        $client = new Client($config);
        $resp = $client->request("post", $this->uploadUrl, [
            'multipart' => [
                [
                    'name' => 'token',
                    'contents' => $this->token,
                ],
                [
                    'name' => 'image',
                    'filename' => basename($fileRoot),
                    'contents' => fopen($fileRoot, 'r'),
//                    'contents' => file_get_contents($fileRoot),
                ],
            ],
        ]);
        $resp_cont = $resp->getBody()->getContents();
        $arr = Tools::isJson($resp_cont);
        if ($arr['code'] != 200) {
            throw new \Exception($resp_cont);
        }
        return $arr['url'];
    }
}